package com.colorlight.cloud.complete.entity.instructions;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.colorlight.cloud.common.exception.ParameterException;
import com.colorlight.cloud.common.model.ExceptionEnum;
import com.colorlight.cloud.complete.api.CompleteEntityScheduleActions;
import com.colorlight.cloud.complete.entity.po.ModuleDeadPixel;
import com.colorlight.iot.proto.complete.instruction.CompleteInstruction;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 获取模组坏点数
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Slf4j
public class GetModuleDeadPixel implements CompleteEntityScheduleActions {

    @Data
    @NoArgsConstructor
    @Builder
    public static class InputMsg implements Serializable {
        // 无参数，点检所有模组
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class OutputMsg implements Serializable {
        /**
         * 模组坏点信息
         */
        private List<ModuleDeadPixel> deadPixel;
        /**
         * 是否正在坏点检测中，如果为true，坏点信息为null
         */
        private Boolean isDoing;
    }

    private InputMsg input;
    private OutputMsg output;

    @Override
    public ByteString objectConvertBytes() {
        final CompleteInstruction.GetModuleDeadPixel.InputMsg.Builder inputMsg =
                CompleteInstruction.GetModuleDeadPixel.InputMsg.newBuilder();
        final CompleteInstruction.GetModuleDeadPixel.Builder builder =
                CompleteInstruction.GetModuleDeadPixel.newBuilder();
        builder.setInput(inputMsg);
        return builder.build().toByteString();
    }

    @Override
    public GetModuleDeadPixel byteConvertObject(ByteString bytes) {
        CompleteInstruction.GetModuleDeadPixel getModuleDeadPixel = null;
        try {
            getModuleDeadPixel = CompleteInstruction.GetModuleDeadPixel.parseFrom(bytes);
        } catch (InvalidProtocolBufferException e) {
            log.error("", e);
        }
        if (Objects.isNull(getModuleDeadPixel)) {
            throw new ParameterException(ExceptionEnum.MSG_PARAMETER_EXCEPTION);
        }
        GetModuleDeadPixel.OutputMsg outputMsg = new GetModuleDeadPixel.OutputMsg();
        CompleteInstruction.GetModuleDeadPixel.OutputMsg output = getModuleDeadPixel.getOutput();
        outputMsg.setDeadPixel(output.getDeadPixelList().stream()
                .map(p -> new ModuleDeadPixel().formProto(p))
                .collect(Collectors.toList()));

        outputMsg.setIsDoing(output.getIsDoing());
        this.setOutput(outputMsg);
        return this;
    }
}

